#!/usr/bin/env python
# -*- coding:utf-8 -*-
from io import BytesIO

import time
from bs4 import BeautifulSoup
from lxml import etree
import requests
import lxml.html
from pytesseract import *
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import requests as req


def login():
    driver = webdriver.PhantomJS()
    driver.get("https://www.douban.com/")
    # 邮箱
    driver.find_element_by_name("form_email").send_keys("215731932@qq.com")
    # 密码
    driver.find_element_by_name("form_password").send_keys("yzl314159")
    driver.save_screenshot("douban_email_password.png")
    # 验证码
    headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"}
    html = requests.get("https://www.douban.com/", headers=headers).text
    bs = BeautifulSoup(html, "lxml")
    captcha_url = bs.find("img", attrs={"id": "captcha_image"}).get("src")
    print(captcha_url)
    response_url = requests.get(captcha_url)
    image = Image.open(BytesIO(response_url.content))
    text = image_to_string(image)
    print("验证码：" + str(text))
    driver.find_element_by_id("captcha_field").send_keys(text)
    # 提交
    driver.find_element_by_class_name("bn-submit").click()
    driver.save_screenshot("douban.png")
    driver.quit()
    print("完成")


def imageTransferText():
    url = "https://www.douban.com/misc/captcha?id=V5qCc8rlB9GylQtfXXeupTRa:en&size=s"
    headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"}
    response_url = requests.get(url, headers=headers)
    with open("captcha.png", "wb") as file:
        file.write(response_url.content)
    time.sleep(3)
    image = Image.open("captcha.png")
    text = image_to_string(image)
    print u"机器识别后的验证码为：" + text


if __name__ == "__main__":
    # login()
    imageTransferText()